import React, { useState } from 'react';
import { Menu, Layout } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import MenuItem from 'antd/es/menu/MenuItem';

const { SubMenu } = Menu;
const { Content } = Layout;
interface MenuItem {
  key: string;
  title: string;
  content?: React.ReactNode; // 允许传递组件作为内容
  subMenu?: MenuItem[];
}





const DynamicMenu: React.FC<{ menus: MenuItem[] }> = ({ menus }) => {
  const [selectedKey, setSelectedKey] = useState<string>(menus[0].key); // 默认选中第一个菜单项

  const handleClick = (e: any) => {
    setSelectedKey(e.key);
  };

  // 根据选中的菜单项渲染不同的内容
  const renderContent = () => {
    for (let menu of menus) {
      if (menu.key === selectedKey) return menu.content;
      const found = menu.subMenu.find(item => item.key === selectedKey);
      if (found) {
        return found.content;
      }
    }
    return <div>请选择一个模块</div>;
  };

  const rendSubMenuTitle = title => {
    return (
      <>
        <span style={{ marginRight: '3px' }}> {title}</span>{' '}
        <DownOutlined style={{ fontSize: '16px', color: 'inherit' }} />
      </>
    );
  };

  return (
    <Layout>
      <Menu mode="horizontal" onClick={handleClick} style={{ fontSize: '16px' }}>
        {menus.map(menu =>
          menu?.subMenu.length > 0 ? (
            <SubMenu key={menu.key} title={rendSubMenuTitle(menu.title)}>
              {menu.subMenu.map(sub => (
                <Menu.Item key={sub.key}>{sub.title}</Menu.Item>
              ))}
            </SubMenu>
          ) : (
            <Menu.Item key={menu.key}>{menu.title}</Menu.Item>
          )
        )}
      </Menu>

      <Content style={{ minHeight: '280px' }}>{renderContent()}</Content>
    </Layout>
  );
};

export default DynamicMenu;
